package com.ibatis4J.framework.dal.resource;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.core.io.Resource;

import com.ibatis4J.framework.dal.exception.DalException;
import com.ibatis4J.framework.dal.resource.parse.SqlBean;
import com.ibatis4J.framework.dal.resource.parse.XmlParser;

/**
 * SQL资源模板解析层
 * 
 * @author liuwenya
 *
 */
public class XmlResource {
	
	/**SQL模板容器*/
	private Map<String,SqlBean> sqlContainer=new HashMap<String,SqlBean>();
	
	/**SQL资源模板*/
	private Resource[] resources;
	
	/**
	 * 默认数据源
	 */
	private DataSource defaultDataSource;

	/**
	 * 设置默认数据源
	 * 
	 * @param defaultDataSource  默认数据源
	 */
	public  void setDefaultDataSource(DataSource defaultDataSource) {
		this.defaultDataSource = defaultDataSource;
	}

	/**
	 * 获取默认数据源
	 * @return  默认数据源
	 */
	public DataSource getDefaultDataSource() {
		return defaultDataSource;
	}
	
	/**
	 * 获取SQL资源模板
	 * @return SQL资源模板
	 */
	public synchronized Resource[] getResources() {
		return resources;
	}
	
	/**
	 * 设置SQL资源模板
	 * @param resources SQL资源模板
	 */
	public synchronized void setResources(Resource[] resources) {
		this.resources = resources.clone();
	}
	
	/**
	 * 解析SQL模板
	 */
	protected void parseResource(){
		XmlParser.getInstance().parser(resources, sqlContainer);
	}
	
	/**
	 * 通过SQLID获取SQLBean
	 * @param sqlId  SQLID
	 * @return  SQL模板映射
	 */
	protected SqlBean getSQL(String sqlId){
		SqlBean sqlBean=sqlContainer.get(sqlId);
		if(sqlBean == null || sqlBean.getContent() == null || "".equals(sqlBean.getContent())){
			throw new DalException("error.dal.003","find sqlId is not have SqlBean");
		}
		return sqlBean;
	}
	
}
